const { Controller } = require('varal');
const { sequelize } = require('../../models');
const { QueryTypes } = require('sequelize');

class CarController extends Controller {
	async index() {
		const { type, page = 1, page_size = 3, category_id = 0, car_category_id, trim } = this.app.fields;

		if (type === 'gallery') {
			let sql = `select
			id,title,images,video_poster,video_src
			from app_article article
			where article.delete_time is null and category_id=2`;

			if (car_category_id) sql += ` and car_category_id='${car_category_id}'`;
			if (trim) sql += ` and trim='${trim}'`;

			const data = await sequelize.query(`${sql} order by sort desc,id asc limit 0,1`, { type: QueryTypes.SELECT });

			return this.app.json({
				err_code: 0,
				data
			})
		} else {
			let sql = `select article.id,title,images,pv,category.name category_name from app_article article left join app_dictionary category on category_id=category.id where article.delete_time is null and is_top=0`;
			if (category_id) sql += ` and (category_id='${category_id}' or category_id in(select id from app_dictionary where find_in_set('${category_id}', parent_ids)))`;
			sql += ` and status='1'`;

			sql += ` order by article.sort desc,article.id desc limit ${((page - 1) * page_size)},${page_size}`;
			const data = await sequelize.query(sql, { type: QueryTypes.SELECT });

			return this.app.json({
				err_code: 0,
				data: data.map((d) => {
					d.thumb = d.images?.split(',')[0];

					return d;
				})
			})
		}
	}

	async latest() {
		const data = await sequelize.query(`select article.id,title,images,pv
		from app_article article
		where article.delete_time is null
		and (category_id='3' or category_id in(select id from app_dictionary where find_in_set('3', parent_ids))) and is_top=1
		order by sort desc,article.id desc limit 0,5`, { type: QueryTypes.SELECT });

		this.app.json({
			err_code: 0,
			data: data.map((d, i) => {
				d.thumb = d.images?.split(',')[0];
				d.first = i === 0 ? 1 : 0;

				return d;
			})
		})
	}

	async promotion() {
		const data = await sequelize.query(`select id,images
		from app_article
		where delete_time is null
		and category_id='4' and is_top=1 and status=1
		order by sort desc,id desc limit 0,1`, { type: QueryTypes.SELECT });

		this.app.json({
			err_code: 0,
			data: data.map((d, i) => {
				d.thumb = d.images?.split(',')[0];
				d.first = i === 0 ? 1 : 0;

				return d;
			})
		})
	}

	async info() {
		const { id } = this.app.fields;
		const articleService = this.app.service('ArticleService');
		const data = await articleService.info({ id });

		this.app.json({
			err_code: 0,
			data
		})
	}
}

exports = module.exports = CarController;
